library(intgrr)

grr.buildData <- function(..., datas=NULL) {
    itemDatas <- c(list(...), datas)
    return(itemDatas)
}

#For multiple items grr summary data.
grr.buildSummary <- function(xdata=NULL) {
    if (is.null(xdata)) {
        print("No data.")
        return(NULL)
    }
    dataLength <- length(xdata)
    result <- NULL
    for (i in 1:dataLength) {
        dt <- xdata[[i]]
        source <- GRRSource(dt$data,dt$appraisers,dt$parts ,dt$trials,dt$sigma,dt$tole)
        GRR <- source$"Tolerance"[5];
        EV <- source$"Tolerance"[1];
        AV <- source$"Tolerance"[2];
        PV <- source$"Tolerance"[6];
        TV <- source$"Tolerance"[7]
        itemGrr <- matrix(c(dt$tole, PV, TV, GRR, EV, AV), ncol=6, byrow=T)
        result <- rbind(result, itemGrr)
    }
    return (result)
}


#For single grr anova and source
grr.buildAnovaAndSource <- function(xdata=NULL) {
    if (is.null(xdata)) {
        print("No data.")
        return(NULL)
    }
    xd <- xdata[[1]]
    itemData <- xd$data
    appraisers <- xd$appraisers
    parts <- xd$parts
    trials <- xd$trials
    sigma <- xd$sigma
    tole <- xd$tole

    anova <- GRRAnova(itemData, appraisers, parts, trials)
    source <- GRRSource(itemData, appraisers, parts, trials, sigma, tole)
    anovaValue <<- round(grr.wrapAnova(anova),bitNum)
    sourceValue <<- round(grr.wrapSource(source),bitNum)
}

grr.wrapAnova <- function(anova) {
    anovaMatrix <- matrix(c(anova$"Df",anova$"Sum Sq",anova$"Mean Sq",anova$"F value",anova$"Pr(>F)"), ncol=5,nrow=5, byrow=F)
    return (anovaMatrix)
}
grr.wrapSource <- function(source) {
    sourceMatrix <- matrix(c(source$"va",source$"Sigma",source$"nSigma",source$"Contribution",source$"Variance",source$"Tolerance"), ncol=6, nrow=7, byrow=F)
    return (sourceMatrix)
}

eval(parse(text=build))
eval(parse(text=funName))
